package com.hp.provider.web;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.common.common.Result;
import com.hp.provider.po.User;
import com.hp.provider.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dongxing
 * @since 2019-05-19
 */
@RestController
@RequestMapping("/mapper/config/user")
@AllArgsConstructor(onConstructor_ = {@Autowired})
@Api(tags = "用户的前端控制器")
@Slf4j
public class UserController {

    private final UserService userService;

    @PostMapping("/findUsers")
    @ApiOperation(value = "分页查询用户的信息")
    public Result findUserById(Integer pageNum, Integer pageSize) {
//        int x = 1 / 0;
        BaseMapper<User> baseMapper = userService.getBaseMapper();
        Page<User> page = new Page<>(pageNum, pageSize);
        IPage<User> userIPage = baseMapper.selectPage(page, new QueryWrapper<User>().lambda().orderByDesc(User::getId));
        return Result.createBySuccess(userIPage);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据用户的id查询用户的信息")
    @SentinelResource(value = "/test", blockHandler = "findUserByIdBlockHandler")
    public Result findUserById(@PathVariable String id) {
        User byId = userService.getById(id);
        return Result.createBySuccess(byId);
    }

    @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
    @SentinelResource(value = "/test", blockHandler = "findUserByIdBlockHandler")
    public String echo(@PathVariable("str") String str) {
        log.info("---------------------");
        return "服务调用成功!" + str;
    }

    @GetMapping("/findAll")
    @ApiOperation(value = "查询所有的信息")
    public Result findAllUsers() {
        List<User> list = userService.findList();
        return Result.createBySuccess(list);
    }

    // Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
    public Result findUserByIdBlockHandler(String id, BlockException ex) {
        log.info("------------------------Begin into findUserByIdBlockHandler ------------------------");
        return Result.createByErrorMessage(ex.getMessage());
    }


    // Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数.
    public Result testFallback(Integer pageNum, Integer pageSize, Throwable ex) {
        log.info("------------------------------Begin into testFallback --------------------------------" + ex.getMessage());
        return Result.createBySuccess(User.builder().userName("哈哈").build());
    }
}
